using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace NBusiness.Query.SqlServer
{
    public sealed class SqlQueryContext : IQueryContext
    {
        private Hashtable _aliases = new Hashtable();
        private uint _aliasCount;

        internal void EnsureAlias(ISource source)
        {
            if (string.IsNullOrEmpty(source.Alias))
                source.Alias = GetNextAlias();

            RegisterAlias(source.Alias);
        }

        private string GetNextAlias()
        {
            string alias = null;
            while (alias == null || _aliases.ContainsKey(alias))
            {
                if (_aliasCount == uint.MaxValue)
                    throw new OverflowException();

                alias = ConvertToBase26(_aliasCount++);
            }
            return alias;
        }

        private void RegisterAlias(string alias)
        {
            if (!_aliases.ContainsKey(alias))
                _aliases.Add(alias, 1);
        }

        private string ConvertToBase26(uint i)
        {
            char c = (char)((i % 26) + 65);
            return (i < 26 ? c.ToString() : ConvertToBase26(i / 26) + c.ToString());
        }
    }
}
